package com.tongdainfo.commom.util;

import java.io.File;
import java.io.InputStream;

import org.junit.Test;

import com.tongdainfo.common.parser.HtmlParser;
import com.tongdainfo.common.parser.IParser;
import com.tongdainfo.common.parser.PdfParser;
import com.tongdainfo.common.parser.TxtParser;
import com.tongdainfo.common.parser.Word2007Parser;
import com.tongdainfo.common.parser.Word98_2003Parser;

/**
 * 读取文本的内容
 * 缺点是无法进行判断是 哪一种的编码集合
 * @author aiju
 *
 */
public class FileToString {
	

	
	/**
	 * 通过文件的路径获取文件的文本内容
	 * @Description:
	 * @param filePath
	 * @return
	 * @author: tianming
	 * @throws Exception 
	 * @time:2017年11月14日 下午5:14:32
	 */
	public static String getFileContent(String filePath) throws Exception{
		File file = new File(filePath);
		IParser  parse = null;
		String extensionName = FileTool.getExtensionName(filePath);
		switch (extensionName) {
		case "doc":
			parse = new Word98_2003Parser();
			break;
		case "docx":
			parse = new Word2007Parser();
			break;
		case "pdf":
			parse = new PdfParser();
			break;
		case "html":
			parse = new HtmlParser();
			break;
		}
		
		String result = parse.readText(file, "GB2312");
		return result;
	}
	
	public static String getFileContent(String filename,InputStream input) throws Exception{
		
		IParser  parse = null;
		String extensionName = FileTool.getExtensionName(filename);
		switch (extensionName) {
		case "doc":
			parse = new Word98_2003Parser();
			break;
		case "docx":
			parse = new Word2007Parser();
			break;
		case "pdf":
			parse = new PdfParser();
			break;
		case "txt":
			parse = new TxtParser();
		case "html":
			parse = new HtmlParser();
			break;
		default:
			return null;
		}
		
//		String result = parse.readText(file, "GB2312");
		String result = null;
		try {
			result = parse.readInput(input,"GB2312");
		} catch (Exception e) {
			try {
				result = parse.readInput(input,"UTF-8");
			} catch (Exception e2) {
				throw new RuntimeException("读取文本失败");
			}
		}
		return result;
	}

}
